<template>
  <div class="article-list" v-if="bol" ref="articleList" @scroll="articleEvent">
    <van-pull-refresh v-model="isLoading" @refresh="refresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多数据了!"
        @load="getData"
      >
        <article-item :item="i" v-for="i in list" :key="i.art_id" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { articlesGet } from '@/api/home.js'
import ArticleItem from './article-item.vue'
export default {
  name: 'ArticleList',
  props: ['id'],
  data () {
    return {
      list: [],
      bol: true,
      isLoading: false,
      loading: false,
      finished: false,
      timestamp: Date.now(),
      scroll: 0
    }
  },
  components: {
    ArticleItem
  },
  methods: {
    async getData () {
      // 发送axios请求,返回时间戳
      const res = await articlesGet({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      // 将返回的数据push进数组
      this.list.push(...res.data.results)
      // 加载完成
      this.loading = false
      // 通过返回的时间戳,判断是否还有下一页
      if (res.data.pre_timestamp) {
        // 有,下一页就将时间戳更新
        this.timestamp = res.data.pre_timestamp
      } else {
        // 没有,停止下拉,显示finished提示
        this.finished = true
      }
      console.log(res)
    },
    refresh () {
      // 上划加载完成,还原上划值
      this.loading = false
      // 隐藏提示
      this.finished = false
      // 还原时间戳
      this.timestamp = Date.now()
      // 还原数组
      this.list = []
      // await this.getData()
      // 下拉刷新完成
      this.isLoading = false
      // 静默刷新
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 滚动事件
    articleEvent () {
      // 将滚动条距离顶部距离保存
      this.scroll = this.$refs.articleList.scrollTop
    }
  },
  // 缓存显示
  activated () {
    // 将保存好滚动条距离的数据设置给滚动条
    this.$refs.articleList.scrollTop = this.scroll
  },
  // 缓存隐藏
  deactivated () {},
  created () {
    // this.getData()
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
